package org.android;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class RegisterView extends Activity {
	
    private static final int ACTIVITY_CREATE = 0;
	
	private EditText password;
	private EditText confirmPassword;
	private Button okButton;
	private Button cancelButton;
	private String passwordCrypted;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);
		
		password = (EditText) findViewById(R.id.passwordReg);
		confirmPassword = (EditText) findViewById(R.id.confirmPasswordReg);
		okButton = (Button) findViewById(R.id.okReg);
		cancelButton = (Button) findViewById(R.id.cancelReg);
		
		okButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (password.getText().toString().equals(
						confirmPassword.getText().toString()))
				{
					TextView uname = (TextView) findViewById(R.id.loginReg);
					try {
						passwordCrypted = MessageDigest.getInstance(
								"MD5").digest(
								password.getText().toString().getBytes())
								.toString();
					} catch (NoSuchAlgorithmException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					// mettre passwordCrypted et tester le md5
					Integer result = WSCommunicator.registerUser(uname
							.getText().toString(), password.getText()
							.toString());
					if (result != 0) {
						Toast.makeText(getBaseContext(),
								"Registration succeed", Toast.LENGTH_SHORT)
								.show();
						goToLogin();
					
					}
					else {
						Toast.makeText(getBaseContext(), "Registration failed",
								Toast.LENGTH_SHORT).show();
					}
				}
				else
					Toast.makeText(getBaseContext(), "Verify your password",
							Toast.LENGTH_SHORT).show();
			}
		});

		cancelButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				if (password.getText().toString().equals(
						confirmPassword.getText().toString()))
					goToLogin();
			}
		});
	}

	protected void goToLogin() {
		Intent i = new Intent(this, LoginView.class);
		startActivityForResult(i, ACTIVITY_CREATE);
	}
}
